/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-10-23     Administrator       the first version
 */
#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#define THREAD_PRIORITY         15
#define THREAD_STACK_SIZE       512
#define THREAD_TIMESLICE        10
#define PULSE_ENCODER_DEV_NAME1    "pulse3"
#define PULSE_ENCODER_DEV_NAME2    "pulse4"

static rt_thread_t tid1 = RT_NULL;

rt_int32_t  count_b = 1000;
rt_int32_t  count_c = 1000;
/* 线程1的入口函数 */
static void thread1_entry(void *parameter)
{
         rt_err_t ret = RT_EOK;
         rt_device_t pulse_encoder_dev = RT_NULL;   /* 脉冲编码器设备句柄 */


         /* 查找脉冲编码器设备 */
         pulse_encoder_dev = rt_device_find(PULSE_ENCODER_DEV_NAME1);
         if (pulse_encoder_dev == RT_NULL)
         {
             rt_kprintf("pulse encoder sample run failed! can't find %s device!\n", PULSE_ENCODER_DEV_NAME1);
             return RT_ERROR;
         }

         /* 以只读方式打开设备 */
         ret = rt_device_open(pulse_encoder_dev, RT_DEVICE_OFLAG_RDONLY);
         if (ret != RT_EOK)
         {
             rt_kprintf("open %s device failed!\n", PULSE_ENCODER_DEV_NAME1);
             return ret;
         }
         rt_device_control(pulse_encoder_dev, PULSE_ENCODER_CMD_ENABLE, RT_NULL);


         /* 查找脉冲编码器设备 */
         pulse_encoder_dev = rt_device_find(PULSE_ENCODER_DEV_NAME2);
         if (pulse_encoder_dev == RT_NULL)
         {
             rt_kprintf("pulse encoder sample run failed! can't find %s device!\n", PULSE_ENCODER_DEV_NAME2);
             return RT_ERROR;
         }

         /* 以只读方式打开设备 */
         ret = rt_device_open(pulse_encoder_dev, RT_DEVICE_OFLAG_RDONLY);
         if (ret != RT_EOK)
         {
             rt_kprintf("open %s device failed!\n", PULSE_ENCODER_DEV_NAME2);
             return ret;
         }
         rt_device_control(pulse_encoder_dev, PULSE_ENCODER_CMD_ENABLE, RT_NULL);


    while (1)
    {
               rt_thread_mdelay(100);
               /* 读取脉冲编码器计数值 */
//               rt_device_read(pulse_encoder_dev, 0, &count, 1);
//               /* 清空脉冲编码器计数值 */
//               rt_device_control(pulse_encoder_dev, PULSE_ENCODER_CMD_CLEAR_COUNT, RT_NULL);
               rt_kprintf("count_b = %d,count_c = %d\t \n",count_b ,count_c);
               count_b = 0; count_c  = 0;
    }
}

int thread_encode_init(void)
{

    /* 创建线程1，名称是thread1，入口是thread1_entry*/
    tid1 = rt_thread_create("encode",
                            thread1_entry, RT_NULL,
                            THREAD_STACK_SIZE,
                            THREAD_PRIORITY, THREAD_TIMESLICE);

    /* 如果获得线程控制块，启动这个线程 */
    if (tid1 != RT_NULL)
        rt_thread_startup(tid1);

    return 0;
}

INIT_APP_EXPORT(thread_encode_init);
